<template>
  <div class="container">
    <div class="add-body">
      <mt-field label="分销商名称："
                placeholder="请输入分销商名称(必填)"
                :attr="{ maxlength: 400 }"
                v-model="department.departmentName"></mt-field>
      <mt-field label="渠道经理："
                readonly
                v-model="managerName"></mt-field>
      <mt-field label="分销商地址："
                placeholder="请输请输入地址信息(必填)"
                :attr="{ maxlength: 400 }"
                v-model="department.address"></mt-field>
      <div class="mint-cell mint-field">
        <div class="mint-cell-wrapper">
          <div class="mint-cell-title">
            <span class="mint-cell-text"></span>
          </div>
          <div class="mint-cell-value"
               style="text-align: left;">
            <a style="font-size: 14px;color:#eb6100"
               @click="goToLocation()">点击获取定位<i class="fa fa-map-marker"></i></a>
          </div>
        </div>
      </div>

      <div class="mint-cell mint-field">
        <div class="mint-cell-wrapper">
          <div class="mint-cell-title">
            <span class="mint-cell-text">省份：</span>
          </div>
          <div class="mint-cell-value">
            <input type="text"
                   name="jjr"
                   placeholder="请选择省份"
                   @click="popupProvince=true"
                   v-model="provinceName"
                   readonly>
          </div>
        </div>
      </div>

      <div class="mint-cell mint-field">
        <div class="mint-cell-wrapper">
          <div class="mint-cell-title">
            <span class="mint-cell-text">城市：</span>
          </div>
          <div class="mint-cell-value">
            <input type="text"
                   name="jjr"
                   placeholder="请选择城市"
                   @click="showCityPopup"
                   v-model="cityName"
                   readonly>
          </div>
        </div>
      </div>

      <mt-popup v-model="popupProvince"
                position="bottom"
                class="mint-popup mint-datetime mint-popup-bottom">
        <div class="">
          <div class="picker-toolbar">
            <div class="mint-datetime-action"
                 style="width:50%;float:left"
                 @click="popupProvince=false">取消</div>
            <div class="mint-datetime-action"
                 style="width:50%;float:left"
                 @click="selectProvince">确定</div>
          </div>
          <mt-picker ref="provincePicker"
                     :slots="provinceSlots"
                     value-key='name'
                     content="name"
                     v-model="id"
                     :item-height="48"
                     @change="onProvinceChange"></mt-picker>
        </div>
      </mt-popup>
      <mt-popup v-model="popupCity"
                position="bottom"
                class="mint-popup mint-datetime mint-popup-bottom">
        <div class="">
          <div class="picker-toolbar">
            <div class="mint-datetime-action"
                 style="width:50%;float:left"
                 @click="popupCity=false">取消</div>
            <div class="mint-datetime-action"
                 style="width:50%;float:left"
                 @click="selectCity">确定</div>
          </div>
          <mt-picker ref="cityPicker"
                     :slots="citySlots"
                     value-key='name'
                     :item-height="48"
                     @change="onCityChange"></mt-picker>
        </div>
      </mt-popup>
    </div>
    <button class="button"
            style="position: fixed;bottom: 0;width: 100%;"
            @click="addOrEditOrg">确定</button>
    <div class="baidu-map"
         v-if="mapShow">
      <BaiduMapContent v-on:address='setAddress'></BaiduMapContent>
    </div>
  </div>
</template>

    <script>
import { Popup, Toast } from "mint-ui";
import BaiduMapContent from "../base/BaiDuMapContent.vue";
export default {
  name: "org-edit",
  components: { Popup, Toast, BaiduMapContent },
  mounted() {
    this.managerName = window.localStorage.getItem("2_userName");
    if (this.$route.params.id) {
      this.getOrg(this.$route.params.id);
    } else {
      this.getProvinceList();
    }
  },
  data() {
    return {
      id: "",
      params: {
        provinceId: "",
        cityId: "",
        userId: window.localStorage.getItem("2_userId")
      },
      department: {
        agentName: "",
        agentManager: "",
        agentAddress: ""
      },
      managerName: "",
      provinceName: "",
      cityName: "",
      popupProvince: false,
      popupCity: false,
      provinceSlots: [],
      citySlots: [],
      provinceIndex: 0,
      cityIndex: 0,
      firstInit: true,
      mapShow: false,
      initFromMap: false
    };
  },
  methods: {
    addOrEditOrg() {
      var _self = this;
      var body = {};
      var url = _self.utilHelper.apiUrl;
      body.params = {
        address: _self.department.address,
        city: _self.params.cityId,
        companyName: _self.department.departmentName,
        province: _self.params.provinceId,
        principal: _self.params.userId
      };
      if (!_self.checkParams()) {
        return;
      }
      if (this.$route.params.id) {
        body.params.id = this.$route.params.id;
        body.params.parentId = _self.department.parentId;
        url += "/api/editAgentDept";
      } else {
        url += "/api/addAgentDept";
      }
      _self.$http.post(url, body).then(response => {
        var resData = response.body.resData;
        if (resData.result == "1") {
          if (this.$route.params.id) {
            this.$router.push("/org/orgIndex");
          } else {
            this.$router.push({
              name: "AddSuccess",
              params: { company: resData.company }
            });
          }
        } else {
          this.$router.push("/org/addOrgFail");
        }
      });
    },
    getOrg(id) {
      var _self = this;
      var body = {};
      body.params = { id: id };
      var url = _self.utilHelper.apiUrl + "/api/getDeptById";
      _self.$http.post(url, body).then(response => {
        var resData = response.body.resData;
        _self.department = resData.department;
        //省市绑定
        _self.getProvinceList();
        _self.params.provinceId = resData.department.province;
        _self.params.cityId = resData.department.province;
        _self.getCityList();
      });
    },
    getProvinceList() {
      var _self = this;
      var body = {};
      body.params = {};
      var url = _self.utilHelper.apiUrl + "/api/getProvince.do";
      _self.$http.post(url, body).then(response => {
        var resData = response.body.resData;
        if (_self.firstInit) {
          _self.params.provinceId = _self.department.province;
        } else {
          _self.params.provinceId = resData.areaList[0].id;
        }
        _self.firstInit = false;

        for (var i in resData.areaList) {
          if (resData.areaList[i].id == _self.department.province) {
            _self.provinceIndex = i;
            _self.provinceName = resData.areaList[i].name;
          }
        }
        _self.provinceSlots.push({
          values: resData.areaList,
          defaultIndex: _self.provinceIndex
        });
      });
    },
    getCityList() {
      console.log("getCityList === >" + new Date());
      var _self = this;
      var provinceId = _self.params.provinceId;
      if (!provinceId) {
        provinceId = 0;
      }
      var url = _self.utilHelper.apiUrl + "/api/getCity.do";
      var body = {};
      body.params = {
        areaId: provinceId
      };
      _self.$http.post(url, body).then(response => {
        var resData = response.body.resData;
        if (response.body.result == "1") {
          this.citySlots = [];
          for (var i in resData.areaList) {
            if (resData.areaList[i].id == _self.department.city) {
              _self.cityIndex = i;
              _self.cityName = resData.areaList[i].name;
              _self.params.cityId = resData.areaList[i].id;
            }
          }
          _self.citySlots.push({ values: resData.areaList, defaultIndex: 26 });
        }
      });
    },
    onProvinceChange(picker, values) {
      this.params.provinceId = values.length ? values[0].id : "";
      this.provinceName = values.length ? values[0].name : "";
      this.getCityList();
    },
    onCityChange(picker, values) {
      if (this.initFromMap) {
        this.initFromMap = false;
        return;
      }
      this.cityName = values.length ? values[0].name : "";
      this.params.cityId = values.length ? values[0].id : "";
    },
    showCityPopup() {
      this.popupCity = true;
      this.getCityList();
    },
    selectProvince() {
      var _self = this;
      if (!_self.params.provinceId) {
        _self.params.provinceId = _self.provinceSlots[0].values[0].id;
        _self.provinceName = _self.provinceSlots[0].values[0].name;
      }
      _self.popupProvince = false;
    },
    selectCity() {
      var _self = this;
      if (!_self.params.cityId) {
        _self.params.cityId = _self.citySlots[0].values[0].id;
        _self.cityName = _self.citySlots[0].values[0].name;
      }
      _self.popupCity = false;
    },
    goToLocation() {
      this.mapShow = true;
    },
    setAddress(data) {
      var _self = this;
      _self.mapShow = false;
      _self.setProvinceAndCityFromMap(data.provinceName, data.cityName);
      if (data) {
        _self.department.address = data.resultAddress;
        _self.provinceName = data.provinceName;
        _self.cityName = data.cityName;
      } else {
      }
    },
    setProvinceAndCityFromMap(provinceName, cityName) {
      var _self = this;
      _self.initFromMap = true;
      //遍历省
      for (var i = 0; i < _self.provinceSlots[0].values.length; i++) {
        if (_self.provinceSlots[0].values[i].name == provinceName) {
          _self.params.provinceId = _self.provinceSlots[0].values[i].id;
          _self.provinceName = _self.provinceSlots[0].values[i].name;
          break;
        }
      }
      _self.$refs.provincePicker.slots[0].defaultIndex = i;
      //获取市区信息 cityPicker
      _self.setCityFromMap(_self.params.provinceId, cityName);
    },
    setCityFromMap(provinceId, cityName) {
      console.log("setCityFromMap === >" + new Date());
      var _self = this;

      var url = _self.utilHelper.apiUrl + "/api/getCity.do";
      var body = {};
      body.params = {
        areaId: provinceId
      };
      _self.$http.post(url, body).then(response => {
        var resData = response.body.resData;
        if (response.body.result == "1") {
          this.citySlots = [];
          for (var k = 0; k < resData.areaList.length; k++) {
            if (resData.areaList[k].name == cityName) {
              _self.cityIndex = k;
              _self.cityName = resData.areaList[k].name;
              _self.params.cityId = resData.areaList[k].id;
              break;
            }
          }
          _self.citySlots.push({ values: resData.areaList, defaultIndex: k });
          _self.$refs.cityPicker.slots[0].defaultIndex = k;
        }
        this.$forceUpdate();
      });
    },
    checkParams() {
      //分销商名称
      var _self = this;
      if (!_self.department.departmentName) {
        Toast("分销商名称不能为空");
        return false;
      }
      if (!_self.department.address) {
        Toast("分销商地址不能为空");
        return false;
      }
      if (!_self.params.provinceId) {
        Toast("请选择省份");
        return false;
      }
      return true;
    }
  }
};
</script>

    <style scoped>
.baidu-map {
  width: 100%;
  height: 100%;
  z-index: 99;
  position: fixed;
  left: 0;
  top: 0;
  background: #fff;
}
</style>